<template>
  <view class="login-container">
    <uni-icons type="contact-filled" size="100" color='#afafaf'></uni-icons>
    <button type="primary" class="btn-login" open-type="getUserInfo" @getuserinfo='userInfoHandler'>一键登录</button>
    <view class="login-text">登录后尽享更多权益</view>
  </view>
</template>

<script setup>
  import { useStore } from 'vuex';
  import { computed } from 'vue';
  const store = useStore();
  const redirectInfo = computed(() => store.state.user.redirectInfo); // 重定向数据
  // 用户授权后,获取用户的基本信息
  function userInfoHandler(e) {
    // console.log('获取到的用户信息', e);
    if(e.detail.errMsg === 'getUserInfo:fail auth deny')  return uni.$showMsg('您取消了登录授权');
    store.commit('user/saveUserInfo', e.detail.userInfo);
    // 获取登录成功后的token字符串
    getToken(e.detail);
  }
  
  function getToken(detail) {
    uni.login({
      success: (res) => {
        console.log('login', res);
        if(res.errMsg !== 'login:ok') return uni.$showMsg('登录失败');
  
        // detail里面包括获取token需要的参数: encryptedData,iv,rawData,signature
        const { encryptedData, iv, rawData, signature } = detail;
        const query = { encryptedData, iv, rawData, signature, code: res.code };
        // 调后端接口获取token
        // const { data: loginRes } = uni.$http.post('/api/public/v1/users/wxlogin', query);
        // if(!loginRes || loginRes.meta.status !== 200) return uni.$showMsg('登录失败');
        // store.commit('user/saveToken', loginRes.message.token);
        
        // 接口调不通,设置一个假的token
        store.commit('user/saveToken', 'dshjdsds57547657454sdjshds');
        navigateBack();
      },
      fail: (err) => {
        uni.$showMsg('登录失败');
      }
    })
  }
  // 重定向回去
  function navigateBack() {
    if(redirectInfo.value) {
      uni[redirectInfo.value.opentype]({
        url: redirectInfo.value.from,
        complete: () => {
          // 返回成功之后,清空vuex中的重定向数据
          store.commit('user/updateRedirectInfo', null);
        }
      })
    }
  }
</script>

<style lang="scss" scoped>
  .login-container {
    height: 750rpx;
    background-color: #f8f8f8;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    position: relative;
    overflow: hidden;
    &::after {
      position: absolute;
      bottom: 0;
      left: 0;
      content: ' ';
      display: block;
      width: 100%;
      height: 40px;
      background-color: white;
      border-radius: 100%;
      transform: translateY(50%);
    }
    .btn-login {
      width: 90%;
      border-radius: 100px;
      margin: 15px 0;
      background-color: #c00000;
    }
    .login-text {
      font-size: 12px;
      color: gray;
    }
  }
</style>